<template>
  <div id="demo-container">
    <div id="mount-point"></div>
    <div class="loading-page">
      <img class="loading-bg" src="./bg.png" alt="">
      <div class="loading-info">
        <img class="loading-logo" src="./bg.png" alt="">
        <p>目前游戏人数较多，请耐心等待</p>
        <p class="loading-queue-index"></p>
        <div class="loading-tips">
          <p class="loading-tips-title">温馨提示</p> 
          <p class="loading-tips-text">无需下载即可体验游戏</p>
          <p class="loading-tips-text">若长时间处于加载阶段，请刷新页面</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { Enqueue,StartProject,Dequeue,heartbeat,StopProject } from '@/api/cloud'
export default {
  data () {
    return {
      form: {
        ProjectId: 'cap-g6q7buoh',
        ApplicationId: 'app-2v5xj92x'
      },
      times: null,
      headers: {
        Authorization: ''
      }
    }
  },
  beforeDestroy () { // 销毁--取消排队、停止云渲染和心跳
    this.getDequeue()
    this.getStopProject()
    clearInterval(this.times)
  },
  created () {
    this.headers.Authorization = this.$route.query.Authorization
    this.times = setInterval(() => {
      this.getHeartbeat()
    }, 1000 * 5) // 5s一次心跳
    // 先取消排队
    this.getStopProject()
    // 再加入排队再启动
    this.getEnqueue()
  },
  methods: {
    // 启动
    getStart() {
      const formData = new FormData()
        formData.set('ProjectId', this.form.ProjectId)
        formData.set('ApplicationId', this.form.ApplicationId)
        formData.set('ClientSession', TCGSDK.getClientSession())
        if(!this.headers.Authorization){
          return 
        }
        StartProject(formData,this.headers).then(res => {
        	if(res.code == 0) {
            TCGSDK.start(res.data.ServerSession)
            document.querySelector('#mount-point').style.display = 'block';
            document.querySelector('.loading-page').style.display = 'none';
          }
        })
    },
    // 页面渲染
    getInfo() {
      let lastX = null;
      let lastY = null;
      TCGSDK.init({
        appid: '1323110658', 
        mount: 'mount-point',
        debugSetting: {
          showLog: true,
        },
        // Connected successfully.
        onConnectSuccess: async (res) => {
          console.log('onConnectSuccess', res);
        },
        // The network was disconnected or the user was kicked out.
        onDisconnect: (res) => {
          console.log('onDisconnect', res);
        },
        onWebrtcStatusChange: (res) => {
          console.log('onWebrtcStatusChange', res);
        },
        // The user touched the mobile client to simulate an instruction sent on a PC.
        onTouchEvent: (res) => {
          // 如果是手游方案，不需要这段逻辑，SDK 内部已经处理
          const { id, type, pageX, pageY } = res.pop();
          // 调用鼠标移动
          TCGSDK.mouseMove(id, type, pageX, pageY);
          // 模拟鼠标点击与抬起
          if (type === 'touchstart') {
            TCGSDK.sendMouseEvent({ type: 'mouseleft', down: true });
          }
          if (type === 'touchend' || type === 'touchcancel') {
            TCGSDK.sendMouseEvent({ type: 'mouseleft', down: false });
          }
        },
        onInitSuccess: async (res) => {
          console.log('%c onInitSuccess', 'color: red', res);
      
          await this.getStart();
        }
      });
      
    },
    // 加入排队
    getEnqueue() {
      Enqueue(this.form,this.headers).then(res => {
        // 排队中
        if (res.code === 10100) {
          document.querySelector('.loading-queue-index').innerHTML = `当前第 ${res.data.index} 位...`;
          // 5s 轮训一次队列
          setTimeout(async () => {
            await this.getEnqueue();
          }, 5000);
        }
        
        // 排队成功
        if (res.code === 10101) {
           this.getInfo();
        }
      })
    },
    //取消排队
    getDequeue(){
      Dequeue(this.form,this.headers).then(res => {
      	
      })
    },
    // 心跳接口
    getHeartbeat(){
      heartbeat(this.form,this.headers).then(res => {
      	
      })
    },
    // 停止云渲染
    getStopProject(){
      StopProject(this.form,this.headers).then(res => {
      	
      })
    }
  }
}
</script>

<style scoped>
  * {
    padding: 0;
    margin: 0;
  }
  
  html,
  body {
    width: 100%;
    height: 100%;
    overflow: hidden;
    font-family: 'SimHei', 'Microsoft YaHei', 'Arial', 'sans-serif';
  }
  
  #demo-container {
    width: 100%;
    height: 100%;
  }
  
  #plugin-point {
    position: absolute;
    left: 100px;
    bottom: 150px;
    width: 0px;
    height: 0px;
  }
  * {
    padding: 0;
    margin: 0;
  }
  
  html,
  body {
    width: 100%;
    height: 100%;
    overflow: hidden;
    font-family: '黑体', 'Microsoft YaHei', 'Arial', 'sans-serif';
  }
  
  #demo-container {
    width: 100%;
    height: 100%;
  }
  
  .loading-page, .loading-bg{
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    color: #000;
    font-size: 12px;
    text-align: center;
  }
  
  .loading-bg {
    background: url('./bg.png') no-repeat;
    background-size: 100% 100%;
    filter: blur(40px);
  }
  
  .loading-info {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    width: 100%;
    color: #131415;
  }
  
  .loading-logo {
    width: 100px;
    height: 100px;
    border-radius: 10px;
    margin-bottom: 10px;
  }
  
  .loading-tips {
    text-align: left;
    width: 80%;
    padding: 20px;
    background-color: rgba(255,255,255, .45);
    margin: 20px auto;
    border-radius: 10px;
  }
  
  .loading-tips-title {
    font-weight: bold;
    color: #131415;
    margin-bottom: 30px;
  }
  
  .loading-tips-text {
    font-family: PingFangSC-Regular;
  }
  
  .button-back {
    width: 50px;
    height: 50px;
    position: absolute;
    bottom: 100px;
    right: 10px;
    touch-action: none;
    user-select: none;
  }
  
  .button-back img {
    width: 100%;
    height: 100%;
  }
    
</style>
